<template>
  <div class="reply_container">
    <div class="name_des flex_row">
      <span class="comments_text">{{ showCommentNum ? commentNum + ' Comments' : '' }}</span>
      <span :class="textarea.length >= 500 ? 'text_num_red' : 'text_num'">
        {{ textarea.length }}/500
      </span>
    </div>
    <div class="mt-[8px]">
      <textarea
        class="custom-textarea"
        ref="textareaRef"
        :placeholder="placeholder"
        v-model="textarea"
        maxlength="500"
        :style="textareaStyle"
        @input="adjustHeight" />
    </div>
    <div class="flex_img">
      <div class="img_item" v-for="(item, index) in fileList">
        <img class="img_item_cover" :key="item.uid" :src="item.url" alt="" />
        <svg
          @click="handleRemove(item)"
          class="del_img cursor_poi"
          xmlns="http://www.w3.org/2000/svg"
          width="10"
          height="10"
          viewBox="0 0 10 10"
          fill="none">
          <path
            d="M7.50433 1.61175C7.74837 1.3677 8.14403 1.36776 8.38811 1.61175C8.63219 1.85583 8.63219 2.25146 8.38811 2.49554L5.88364 4.99961L8.38811 7.50408C8.63219 7.74816 8.63219 8.14379 8.38811 8.38787C8.14404 8.63195 7.7484 8.63195 7.50433 8.38787L4.99985 5.8834L2.49578 8.38787C2.2517 8.63195 1.85607 8.63195 1.61199 8.38787C1.36798 8.14379 1.36794 7.74814 1.61199 7.50408L4.11606 4.99961L1.61199 2.49554C1.36796 2.25146 1.36793 1.85581 1.61199 1.61175C1.85606 1.36768 2.2517 1.36771 2.49578 1.61175L4.99985 4.11582L7.50433 1.61175Z"
            fill="#CBCBCB" />
        </svg>
      </div>
    </div>
    <div class="flex_row mt-[8px]">
      <el-upload
        v-if="isCanUpImg"
        class="upload-el"
        :show-file-list="false"
        :file-list="fileList"
        :http-request="handleCustomUpload"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        accept="image/*">
        <span class="line choose_img" v-slide-underline>Choose Picture</span>
      </el-upload>
      <div v-else></div>
      <div
        v-show="fileList?.length > 0 || textarea?.length > 0"
        v-hover-bg
        class="send_comment flex_row cursor_poi"
        @click="reply">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none">
          <path
            d="M17.7054 5.0025C16.084 3.70526 14.0692 2.99898 11.9928 3C9.54512 3 7.25896 3.94299 5.54977 5.6554C3.89803 7.31237 2.99281 9.50009 3.00004 11.814C3.0001 13.5104 3.49814 15.1696 4.43241 16.5856L4.44004 16.5964C4.45129 16.6129 4.46294 16.6294 4.47459 16.6454C4.48624 16.6615 4.50071 16.6824 4.50392 16.6876L4.51276 16.7037C4.55816 16.7841 4.59312 16.8821 4.56218 16.9809L3.82209 19.6592C3.79249 19.7588 3.77627 19.8619 3.77388 19.9658C3.77335 20.2391 3.8812 20.5014 4.07378 20.6953C4.26637 20.8891 4.52798 20.9987 4.80124 21C4.94564 20.9952 5.08795 20.964 5.22111 20.908L7.93275 19.9292L7.96691 19.916C8.04067 19.885 8.11994 19.8693 8.19994 19.8698C8.2737 19.87 8.34682 19.8836 8.4157 19.91C8.48079 19.9353 9.07181 20.1615 9.69538 20.3358C10.2137 20.4805 11.2921 20.6975 12.137 20.6975C14.5337 20.6975 16.7716 19.7693 18.4382 18.0834C20.0904 16.4104 21 14.1865 21 11.8188C21.0002 11.211 20.9358 10.6049 20.8079 10.0108C20.3925 8.05728 19.2908 6.27817 17.7054 5.0025ZM8.14289 13.2857C7.8886 13.2857 7.64002 13.2103 7.42859 13.069C7.21715 12.9278 7.05236 12.727 6.95505 12.492C6.85773 12.2571 6.83227 11.9986 6.88188 11.7492C6.93149 11.4998 7.05394 11.2707 7.23375 11.0909C7.41356 10.9111 7.64265 10.7886 7.89206 10.739C8.14146 10.6894 8.39997 10.7148 8.63491 10.8122C8.86984 10.9095 9.07064 11.0743 9.21192 11.2857C9.35319 11.4971 9.4286 11.7457 9.4286 12C9.4286 12.341 9.29314 12.668 9.05202 12.9091C8.8109 13.1503 8.48388 13.2857 8.14289 13.2857ZM12 13.2857C11.7457 13.2857 11.4972 13.2103 11.2857 13.069C11.0743 12.9278 10.9095 12.727 10.8122 12.492C10.7149 12.2571 10.6894 11.9986 10.739 11.7492C10.7886 11.4998 10.9111 11.2707 11.0909 11.0909C11.2707 10.9111 11.4998 10.7886 11.7492 10.739C11.9986 10.6894 12.2571 10.7148 12.492 10.8122C12.727 10.9095 12.9278 11.0743 13.0691 11.2857C13.2103 11.4971 13.2857 11.7457 13.2857 12C13.2857 12.341 13.1503 12.668 12.9092 12.9091C12.668 13.1503 12.341 13.2857 12 13.2857ZM15.8572 13.2857C15.6029 13.2857 15.3543 13.2103 15.1429 13.069C14.9314 12.9278 14.7666 12.727 14.6693 12.492C14.572 12.2571 14.5465 11.9986 14.5961 11.7492C14.6458 11.4998 14.7682 11.2707 14.948 11.0909C15.1278 10.9111 15.3569 10.7886 15.6063 10.739C15.8557 10.6894 16.1142 10.7148 16.3492 10.8122C16.5841 10.9095 16.7849 11.0743 16.9262 11.2857C17.0675 11.4971 17.1429 11.7457 17.1429 12C17.1429 12.341 17.0074 12.668 16.7663 12.9091C16.5252 13.1503 16.1981 13.2857 15.8572 13.2857Z"
            fill="white" />
        </svg>
        <span class="ml-[8px]">{{ sendText }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue';
  import {
    ElMessage,
    ElMessageBox,
    UploadFile,
    UploadProps,
    UploadRawFile,
    UploadUserFile,
  } from 'element-plus';
  import { BaseAPI } from '@/api/base';

  const emit = defineEmits(['postComment']);
  const props = defineProps({
    showCommentNum: { type: Boolean, default: false },
    commentNum: { type: Number, default: 0 },
    sendText: { type: String, default: 'Send' },
    placeholder: { type: String, default: 'Enter your comments' },
    replyItem: { type: Object, default: () => {} },
    isCanUpImg: { type: Boolean, default: true },
  });

  const textarea = ref<string>(''); // 文本框值
  const fileList = ref<any>([]);
  // 文本框引用
  const textareaRef = ref<any>(null);

  const baseStyles = {
    minHeight: '40px',
    maxHeight: '80px',
    paddingTop: '8px',
    paddingBottom: '8px',
    paddingLeft: '16px',
    paddingRight: '16px',
    boxSizing: 'border-box' as const,
    resize: 'none' as const,
    overflow: 'auto' as const,
    // 可根据需要添加其他基础样式
    borderRadius: '8px',
    fontSize: '14px',
    width: '100%',
    background: '#EDEDED',
    lineHeight: '21px',
    color: '#222',
    // 隐藏滚动条相关样式
    scrollbarWidth: 'none' as const, // Firefox
    msOverflowStyle: 'none' as const, // IE and Edge
    // 基础样式 - 移除默认边框和轮廓
    border: 'none',
    outline: 'none',
    transition: 'background-color 0.2s ease', // 背景色过渡动画
  };

  // 计算文本框样式
  const textareaStyle = computed(() => ({
    ...baseStyles,
  }));

  // 初始化时调整高度
  onMounted(() => {
    adjustHeight();
  });

  // 定义聚焦方法
  const focusTextarea = () => {
    textareaRef.value?.focus(); // 调用原生focus()方法
  };

  // 调整高度的方法
  const adjustHeight = () => {
    if (!textareaRef.value) return;

    // 先将高度设为最小高度，以便正确计算滚动高度
    textareaRef.value.style.height = baseStyles.minHeight;

    // 计算内容所需高度
    const scrollHeight = textareaRef.value.scrollHeight;

    // 根据最大高度限制设置最终高度
    if (scrollHeight <= parseInt(baseStyles.maxHeight)) {
      textareaRef.value.style.height = `${scrollHeight}px`;
    } else {
      textareaRef.value.style.height = baseStyles.maxHeight;
    }
  };

  const reply = () => {
    if (!textarea.value && fileList.value.length === 0) return;
    emit('postComment', {
      content: textarea.value,
      images: fileList.value,
      replyItem: props.replyItem,
    });
  };

  // 自定义上传方法
  const handleCustomUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    try {
      // 调用实际的文件上传接口
      const response = await BaseAPI.uploadFile(file);
      // 假设响应中包含文件的URL
      const fileUrl = response.data.url;
      // 更新文件列表
      const item = [
        {
          name: file.name,
          url: fileUrl,
          uid: file.uid || `file_${Date.now()}`,
          raw: file,
          status: 'ready',
        },
      ];
      fileList.value = fileList.value.concat(item);
      // 通知组件上传成功
    } catch (error) {
      // 通知组件上传失败
      console.error('文件上传失败:', error);
    }
  };

  // 文件上传前的验证方法
  const beforeUpload = (file: UploadRawFile) => {
    // 定义最大文件大小 (20MB)
    const maxSize = 20 * 1024 * 1024;
    // 最多上传3张
    if (fileList.value?.length >= 3) {
      ElMessage.warning('You can upload a maximum of three images');
      return false;
    }

    // 检查文件大小
    if (file.size && file.size > maxSize) {
      ElMessage.error('The file size cannot exceed 20M');
      return false;
    }
    // 验证通过，继续上传
    return true;
  };

  // 处理文件删除
  const handleRemove = (file: UploadFile) => {
    const index = fileList.value.findIndex((item: any) => item.uid === file.uid);
    if (index !== -1) {
      fileList.value.splice(index, 1);
    }
    return true;
  };

  const clear = () => {
    textarea.value = '';
    fileList.value = [];
    if (!textareaRef.value) return;
    textareaRef.value.style.height = baseStyles.minHeight;
  };

  const handlePreview: UploadProps['onPreview'] = (uploadFile: any) => {
    console.log(uploadFile);
  };

  const handleExceed: UploadProps['onExceed'] = (files: any, uploadFiles: any) => {
    ElMessage.warning(
      `The limit is 3, you selected ${files.length} files this time, add up to ${
        files.length + uploadFiles.length
      } totally`
    );
  };

  const beforeRemove: (uploadFile: any, uploadFiles: any) => Promise<boolean> = (
    uploadFile: any,
    uploadFiles: any
  ) => {
    return ElMessageBox.confirm(`Cancel the transfer of ${uploadFile.name} ?`).then(
      () => true,
      () => false
    );
  };

  defineExpose({
    clear,
    focusTextarea,
  });
</script>

<style lang="scss" scoped>
  .reply_container {
    .custom-textarea {
      display: block;
    }

    .custom-textarea:hover {
      background: #e1e2e3 !important;
    }
    .flex_img {
      display: flex;
      flex-direction: row;
      align-items: center;
      .img_item {
        width: 56px;
        height: 56px;
        margin-right: 5px;
        margin-top: 8px;
        border-radius: 8px;
        overflow: hidden;
        position: relative;
      }
      .img_item_cover {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
      .del_img {
        position: absolute;
        right: 5px;
        top: 5px;
      }
    }
    .cursor_poi {
      cursor: pointer;
    }
    .line {
      display: inline-block;
      background-image: linear-gradient(to right, #cbcbcb, #cbcbcb);
      background-size: 100% 2px;
      background-position: bottom;
      background-repeat: no-repeat;
    }
    .choose_img {
      color: #222;
      font-size: 14px;
      font-weight: 500;
      line-height: 21px; /* 21px */
    }
    ::v-deep .custom-scrollbar-textarea .el-textarea__inner {
      -webkit-appearance: none;
      background-color: #ededed;
      border: none;
      border-radius: 8px;
      //box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
      box-sizing: border-box;
      color: #222;
      display: block;
      font-size: 14px;
      position: relative;
      resize: none;
      transition: var(--el-transition-box-shadow);
      width: 100%;
      //min-height: 40px;
      max-height: 180px;
      padding: 10px 16px;
      line-height: 21px;
      overflow: auto;
      /* 基础样式：确保内容超出时显示滚动条 */
      resize: none; /* 禁用手动拉伸（可选） */
      overflow-y: auto; /* 垂直滚动条按需显示 */
      /* Firefox 滚动条样式（简单调整） */
      scrollbar-width: thin; /* 滚动条宽度：auto/thin/none */
      scrollbar-color: #ccc #f5f5f5; /* 滑块颜色 轨道颜色 */
    }

    /* WebKit 内核浏览器（Chrome/Edge/Safari）滚动条样式 */
    /* 滚动条整体宽度 */
    ::v-deep .custom-scrollbar-textarea .el-textarea__inner::-webkit-scrollbar {
      width: 6px; /* 垂直滚动条宽度 */
      height: 6px; /* 水平滚动条高度（如需） */
    }
    /* 滚动条轨道 */
    ::v-deep .custom-scrollbar-textarea .el-textarea__inner::-webkit-scrollbar-track {
      background: #f5f5f5; /* 轨道背景色 */
      border-radius: 3px; /* 轨道圆角 */
    }
    /* 滚动条滑块（未 hover 时） */
    ::v-deep .custom-scrollbar-textarea .el-textarea__inner::-webkit-scrollbar-thumb {
      background: #ccc; /* 滑块颜色 */
      border-radius: 3px; /* 滑块圆角 */
    }
    /* 滚动条滑块（hover 时） */
    ::v-deep .custom-scrollbar-textarea .el-textarea__inner::-webkit-scrollbar-thumb:hover {
      background: #999; /* 滑块 hover 颜色 */
    }
    /* 滚动条角落（垂直+水平滚动条交汇处） */
    ::v-deep .custom-scrollbar-textarea .el-textarea__inner::-webkit-scrollbar-corner {
      background: #f5f5f5; /* 角落背景色 */
    }

    .send_comment {
      border-radius: 8px;
      background: #f76b1b;
      padding: 6px 16px;
      color: #fff;
      font-size: 16px;
      font-weight: 500;
    }
    .name_des {
      color: #7a7a7a;
      font-size: 16px;
      line-height: 16px;
    }
    .flex_row {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      //align-items: center;
    }
    .text_num_red {
      color: #ff4d4f;
      font-size: 14px;
    }

    .text_num {
      color: #7a7a7a;
      font-size: 14px;
    }
  }
  .comments_text {
    font-weight: 500;
  }
</style>
